package com.gxsyh.nantie.login.provider.controller;

import com.google.common.collect.Maps;
import com.gxsyh.nantie.commons.dto.ResponseResult;
import com.gxsyh.nantie.commons.utils.MapperUtils;

import com.gxsyh.nantie.commons.utils.OkHttpClientUtil;
import com.gxsyh.nantie.login.provider.domain.TbUser;
import com.gxsyh.nantie.login.provider.service.TbUserService;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * @email yom535@outlook.com
 * @author: 刘锋嘉(Liu Fengjia)
 * @date: 2020/1/19
 * @time: 13:47
 * @Description:
 */
@RestController
public class RefreshController {
    @Resource
    TbUserService tbUserService;

    @Value("${server.port}")
    String ServerPort;


    @GetMapping(value = "/users/phone/refresh")
    public ResponseResult<Map<String, Object>> refresh() throws Exception {

        String URL_OAUTH_TOKEN="http://127.0.0.1:"+ServerPort+"/oauth/token";

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TbUser tbUser = tbUserService.selectOneTbUserById(Long.valueOf(authentication.getName()));
        String refresh_token = tbUser.getRefresh_token();
        Map<String,String> params= Maps.newHashMap();
        params.put("refresh_token", refresh_token);
        params.put("grant_type", "refresh_token");
        params.put("client_id", "phone");
        params.put("client_secret", "secretphone");
        Response response = OkHttpClientUtil.getInstance().postData(URL_OAUTH_TOKEN, params);
        String jsonString= Objects.requireNonNull(response.body()).string();
        Map<String, Object> jsonMap = MapperUtils.json2map(jsonString);
        String token = String.valueOf(jsonMap.get("access_token"));
        Map<String,Object> result=Maps.newHashMap();
        result.put("token",token);
        return new ResponseResult<Map<String, Object>>(HttpStatus.OK.value(),"刷新成功",result);
    }
}
